package com.csust.travel.service.impl;

import org.springframework.stereotype.Service;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

@Service
public class CodeService {
    private static final ConcurrentHashMap<String, String> codeCache = new ConcurrentHashMap<>();

    public void generateAndCacheCode(String email) {
        // 生成 6 位随机数验证码
        String code = cn.hutool.core.util.RandomUtil.randomNumbers(6);

        // 将验证码存储到缓存中，并设置过期时间为 5 分钟
        codeCache.put(email, code);
        new Thread(() -> {
            try {
                TimeUnit.MINUTES.sleep(5);
                codeCache.remove(email);
                System.out.println("Removed expired code for " + email);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        System.out.println("Generated and cached code for " + email + ": " + code);
    }

    public String getAndKeepCode(String email) {
        String code = codeCache.get(email);
        System.out.println("Fetched code for " + email + ": " + code);
        return code;
    }

    public String getAndRemoveCode(String email) {
        String code = codeCache.remove(email);
        System.out.println("Removed code for " + email + ": " + code);
        return code;
    }

    public boolean validateCode(String email, String code) {
        String cachedCode = codeCache.get(email);
        System.out.println("Validating code for " + email + ": " + code + " (cached: " + cachedCode + ")");
        if (cachedCode != null && cachedCode.equals(code)) {
            codeCache.remove(email);
            System.out.println("Validation successful for " + email);
            return true;
        }
        System.out.println("Validation failed for " + email);
        return false;
    }
}
